<template>
    <div class="upload-icon">
        <div class="upload-icon-box">
            <i class="icon icon-add" v-if="!img"></i>
            <img v-else :src="img">
            <input type="file" accept="image/*" @change="upLoadImg" ref="input">
        </div>
        <div class="upload-icon-txt" @click="triggerUpLoad">上传图标</div>
    </div>
</template>

<script type="text/javascript">
    export default{
        data() {
            return {
                img:this.url
            }
        },
        props: {
            url: {
                type: String,
                default: ''
            },
        },

        methods: {
            triggerUpLoad(){
                this.$refs.input.click()
            },
            upLoadImg(event){
                let vm = this
                let file = event.target.files[0] //获取文件信息

                if(!file) return false 
                
                let type = file.type
                
                //验证文件类型
                if (type === "image/jpeg" || type === "image/jpg" || type === "image/png") {

                    //验证图片大小
                    if(file.size > 2 * 1024 * 1024){
                        console.log('图片大小超过 2 M');
                        return false;
                    }

                    //图片本地预览
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var url = e.target.result;                        
                        vm.img = url;  //触发action更改本地url
                    };
                    reader.readAsDataURL(file);
                }
            }
        },
        mounted () {

        }
    }
</script>

<style lang="less" scope>
  @import url('../../assets/less/style.less');

    .upload-icon{
        // line-height: 80px;
        margin-left: 15px; 
        margin-top: 15px;
        color: @gray;
        .flexbox();
        .justify-content(start);
        .align-items(center);
        &-box{                
            text-align: center;  
            border:solid 3px @gray1;  
            border-radius: 5px;
            width: 80px;
            height: 80px;
            margin-right: 5px;  
            position: relative;
            .flexbox();
            .justify-content(center);
            .align-items(center);
        }
        input[type="file"]{
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            opacity: 0;
        }
        img{
            max-width: 100%;
            max-height: 100%;
        }
    }
</style>